package com.jsn.exception;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.jsn.responseEntity.CommonCode;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;


/**
 * AuthenticationEntryPoint 用来解决匿名用户访问无权限资源时的异常
 * 自定义异常信息
 */
public class SmartAuthExceptionEntryPoint implements AuthenticationEntryPoint {

    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws ServletException {
        CommonCode resultEnum = CommonCode.INVALID_TOKEN;
        Map map = new HashMap();
        map.put("code", resultEnum.code());
        map.put("msg", resultEnum.message());
        response.setContentType("application/json");
        response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
        try {
            ObjectMapper mapper = new ObjectMapper();
            mapper.writeValue(response.getOutputStream(), map);
        } catch (Exception e) {
            throw new ServletException();
        }
    }
}